<template>
  <div>
    <the-table
      :data="types"
      :pageInfo="queryInfo"
      :total="total"
      @pageInfoChange="pageInfoChange"
      @handleAdd="showAddDialog"
      :layout="['addBtn', 'search', 'column']"
      :columns="columns"
      @changeColumn="changeColumn"
      @search="search"
      @clearInput="getType"
    >
      <!-- 表格区 -->
      <el-table-column label="id" prop="id" v-if="columns[0].show">
      </el-table-column>
      <el-table-column label="分类名" prop="type" v-if="columns[1].show">
      </el-table-column>
      <!-- 操作区域 -->
      <el-table-column label="操作" width="200px" v-if="columns[2].show">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            style="color: #409eff"
            @click="showEditType(scope.row)"
          >
            <el-icon class="el-input__icon"><edit /></el-icon> 编辑
          </el-button>
          <el-button
            size="small"
            type="text"
            style="color: #f56c6c"
            @click="removeById(scope.row.id)"
          >
            <el-icon class="el-input__icon"><delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <!-- 对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input v-model="newType"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  addType,
  editType,
  deleteType,
  getTypeReq,
  searchTypeByName
} from "@/api/CourseManagement/courseType";
import { addLogs } from "@/api/Home/Home";
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import TheTable from "@/components/common/TheTable.vue";

export default {
  name: "CourseCatrgory",
  components: { TheTable },
  setup() {
    const state = reactive({
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        isShow: true,
        placeholder: '请输入分类名称'
      },
      types: [],
      dialogTitle: "添加分类", // 对话框标题
      dialogVisible: false,
      newType: "",
      editFlag: "false",
      // 统计课程分类的总数量
      total: 0,
      columns: [
        { name: "Id", show: true },
        { name: "分类名", show: true },
        { name: "操作", show: true },
      ],
    });
    async function search(searchText) {
      await searchTypeByName(searchText).then((res) => {
        console.log(res)
      })
    }
    // 改变表单栏显示隐藏状态
    function changeColumn(columns) {
      state.columns = columns;
    }
    // 获取所有课程
    async function getType() {
      await getTypeReq(state.queryInfo.pageNum, state.queryInfo.pageSize).then(
        (res: { data: any }) => {
          const result = res.data;
          console.log(result);
          if (result.ret === 0) {
            state.types = result.courseTypes.types.content;
            state.total = result.courseTypes.types.totalElements;
          } else {
            ElMessage.error("服务器请求错误！");
          }
        }
      );
    }
    function showAddDialog() {
      state.dialogTitle = "添加分类";
      state.editFlag = "false";
      state.dialogVisible = true;
      state.newType = "";
    }
    function handleClose(done: () => void) {
      state.newType = "";
      state.dialogVisible = false;
    }
    async function submit() {
      if (!state.newType) {
        return ElMessage.error("请输入类型名称！");
      }
      if (state.editFlag !== "false") {
        await editType(state.editFlag, state.newType).then(async (res) => {
          if (res.status === 200) {
            ElMessage.success("修改类型成功！");
            state.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "修改了<" + state.newType + ">分类",
            });
            getType();
          } else {
            ElMessage.error("修改类型出错！");
          }
        });
      } else {
        await addType(state.newType).then(async (res) => {
          if (res.status === 200) {
            ElMessage.success("添加类型成功！");
            state.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "添加了<" + state.newType + ">分类",
            });
            getType();
          } else {
            ElMessage.error("添加类型出错！");
          }
        });
      }
    }
    // 搜索课程
    async function searchCourse() {
      // if (!state.queryInfo.query) {
      //   return ElMessage.error("请输入名称");
      // }
      // state.queryInfo.pageNum = 1;
      // await searchCourse(state.queryInfo).then((res) => {
      //   if (res && res.status === 200) {
      //     state.types = res.data.courses.courses.content;
      //     state.total = res.data.courses.courses.totalElements;
      //     if (state.types === []) {
      //       ElMessage.info("搜索结果为空");
      //     } else {
      //       ElMessage.success("搜索成功！");
      //     }
      //   } else {
      //     ElMessage.error(res.data.msg);
      //   }
      // });
    }
    // 清除输入框的内容
    function clearInput() {
      state.queryInfo.pageNum = 1;
      state.queryInfo.pageSize = 5;
      getType();
    }
    // 打开编辑课程对话框
    function showEditType(row: { id: boolean; type: string }) {
      state.editFlag = row.id;
      state.newType = row.type;
      state.dialogTitle = "修改分类";
      state.dialogVisible = true;
    }
    // 删除课程
    async function removeById(id: any) {
      const confirmResult = await ElMessageBox.confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err: any) => err);
      if (confirmResult === "confirm") {
        await deleteType(id).then((res: any) => {
          if (res.status === 200) {
            ElMessage.success("成功删除该分类！");
            getType();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      }
    }
    // 分页数据改变
    function pageInfoChange(type: string, newValue: number) {
      console.log(type, newValue);
      if (type === "size") state.queryInfo.pageSize = newValue;
      else if (type === "page") state.queryInfo.pageNum = newValue;
      getType();
    }

    getType();

    return {
      ...toRefs(state),
      getType,
      showAddDialog,
      handleClose,
      submit,
      search,
      searchCourse,
      clearInput,
      showEditType,
      removeById,
      pageInfoChange,
      changeColumn,
    };
  },
};
</script>

<style lang="scss"></style>
